package cc.mrbird.febs.buss.controller;

import cc.mrbird.febs.buss.entity.ConnPolicyFile;
import cc.mrbird.febs.buss.service.IConnPolicyFileService;
import cc.mrbird.febs.buss.util.ConvertUtil;
import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.buss.entity.TFile;
import cc.mrbird.febs.buss.service.ITFileService;
import cc.mrbird.febs.system.entity.Dept;
import cc.mrbird.febs.system.service.IDeptService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.*;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 *  Controller
 *
 * @author Lujingyuan
 * @date 2020-11-27 09:48:09
 */
@Slf4j
@Validated
@Controller
public class TFileController extends BaseController {

    @Autowired
    private ITFileService tFileService;
    @Autowired
    private IConnPolicyFileService connPolicyFileService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "tFile")
    public String tFileIndex(){
        return FebsUtil.view("tFile/tFile");
    }

    @GetMapping("tFile")
    @ResponseBody
    @RequiresPermissions("tFile:list")
    public FebsResponse getAllTFiles(TFile tFile) {
        return new FebsResponse().success().data(tFileService.findTFiles(tFile));
    }

    @GetMapping("tFile/list")
    @ResponseBody
    public FebsResponse tFileList(QueryRequest request, HttpServletRequest req, TFile tFile) {
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        Map<String, Object> dataTable = getDataTable(this.tFileService.findTFileDetail(request, map));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "tFile/add")
    public String goTFileAdd() {
        return FebsUtil.view("tFile/tFileAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "tFile/update/{id}")
    public String goTFileUpdate(@PathVariable String id, Model model) {
        TFile obj= tFileService.getById(id);
        model.addAttribute("obj",obj);
        return FebsUtil.view("tFile/tFileUpdate");
    }

    @ControllerEndpoint(operation = "新增TFile", exceptionMessage = "新增TFile失败")
    @PostMapping("tFile")
    @ResponseBody
    public FebsResponse addTFile(@Valid TFile tFile) {
        this.tFileService.createTFile(tFile);
        return new FebsResponse().success();
    }

    @GetMapping("tFile/delete/{objIds}")
    @ControllerEndpoint(operation = "删除", exceptionMessage = "删除失败")
    @ResponseBody
    public FebsResponse deleteTFile( @PathVariable String objIds) {
        String[] ids = objIds.split(StringPool.COMMA);
        this.tFileService.deleteTFile(ids);
        //同时删除政策和文件关联
        for (String fileId : ids) {
            QueryWrapper<ConnPolicyFile> wrapper = new QueryWrapper<>();
            wrapper.eq("file_id",fileId);
            connPolicyFileService.remove(wrapper);
        }

        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "修改TFile", exceptionMessage = "修改TFile失败")
    @PostMapping("tFile/update")
    @ResponseBody
    public FebsResponse updateTFile(TFile tFile) {
        this.tFileService.updateTFile(tFile);
        return new FebsResponse().success();
    }


    /**
     * 根据政策id查寻相关的文件
     * @param policyId
     * @return
     */
    @GetMapping("tFile/getFilesByPolicyId/{policyId}")
    @ResponseBody
    public FebsResponse getFilesByPolicyId(@PathVariable String policyId){
        ArrayList<TFile> files = new ArrayList<>();
        QueryWrapper<ConnPolicyFile> wrapper = new QueryWrapper<>();
        wrapper.eq("policy_id",policyId);
        List<ConnPolicyFile> connPolicyFiles = connPolicyFileService.list(wrapper);
        for (ConnPolicyFile connPolicyFile : connPolicyFiles) {
            TFile file = tFileService.getById(connPolicyFile.getFileId());
            files.add(file);
        }
        return new FebsResponse().success().data(files);
    }

    /**
     * 图片/文件上传
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "tFile/fileUpload")
    @ResponseBody
    public FebsResponse fileUpload(@RequestParam(value = "file") MultipartFile file,
                                   HttpServletRequest request,
                                   HttpServletResponse response)
            throws IOException {
        StringBuffer sb=new StringBuffer();
        String msg="上传成功";
        String src="http://localhost:8085/tFile/preFile/";
        Integer code=0;
        if (file.isEmpty()) {
            System.out.println("文件为空");
            code=1;
            msg="上传失败";
        }
        TFile tfile=new TFile();
        String fileName = file.getOriginalFilename();  // 文件名
        tfile.setRealName(fileName);
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名

        suffixName = suffixName.toLowerCase();//转小写


        String filePath = "D://queue_file//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名

        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);
        //文件上传到本地后，判断文件类型，调用工具类转化成pdf
        if(suffixName.equalsIgnoreCase(".doc") || suffixName.equalsIgnoreCase(".docx")){
            boolean b = ConvertUtil.word2Pdf(fileName, "D://queue_file", "D://queue_file");
            fileName = b?fileName.substring(0,fileName.lastIndexOf("."))+ ".pdf" : fileName;
        }
        tfile.setFileName(fileName);
        tfile.setFileType(suffixName);
        tfile.setCreateTime(new Date());
        tfile.setFilePath(filePath+fileName);
        this.tFileService.createTFile(tfile);

            //src+=tfile.getId();

//        sb.append("{");
//
//        sb.append("\"code\":"+code);
//        sb.append(",");
//
//        sb.append("\"msg\":\""+msg+"\"");
//        sb.append(",");
//
//        sb.append("\"data\":{\"src\":\""+src+"\",\"title\":\""+fileName+"\"}");
//
//        sb.append("}");
        //response.getWriter().write(sb.toString());
        return new FebsResponse().success().data(tfile);
    }


    /**
     * 预览图片
     *
     * @throws IOException
     * @throws Exception
     */
    @GetMapping("tFile/preFile/{id}")
    public void prePhoto(@PathVariable String id, HttpServletResponse response) throws IOException {

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        OutputStream os = null;
        InputStream is = null;

        QueryWrapper<ConnPolicyFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("policy_id", id);
        List<ConnPolicyFile> connPolicyFiles = connPolicyFileService.list(queryWrapper);
        if (connPolicyFiles != null && connPolicyFiles.size() > 0) {

            for (ConnPolicyFile connPolicyFile : connPolicyFiles) {
                Long fileId = connPolicyFile.getFileId();
                TFile file = this.tFileService.getById(fileId);
                if (file != null) {
                    String filePath = file.getFilePath();
                    is = new FileInputStream(filePath);
                    bis = new BufferedInputStream(is);
                    os = response.getOutputStream();
                    bos = new BufferedOutputStream(os);
                    int byteRead = 0;
                    byte[] buffer = new byte[5 * 1024];
                    while ((byteRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, byteRead);
                    }
                    bos.close();
                    bis.close();
                    os.close();
                    is.close();

                }
            }

        }

    }
}
